package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wjh
 * @create 2023-07-12
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private WorkspaceService workspaceService;

    /**
     * 日期区间转日期集合
     * @param begin
     * @param end
     * @return
     */
    public List<LocalDate> LocalDateIntervalToList(LocalDate begin, LocalDate end){
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            localDateList.add(begin = begin.plusDays(1));
        }
        return localDateList;
    }

    public Map<String,Object> LocalDateToLocalDateTimeMap(LocalDate localDate){
        //因为数据库的日期带有时分秒，而LocalDate只有年月日，所以要获得当前时间的最小开始时间和最大结束时间
        LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
        //SELECT SUM(amount) FROM `orders` WHERE `status` = 5 AND order_time >beginTime AND order_time < endTime
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("begin",beginTime);
        hashMap.put("end",endTime);
        return hashMap;
    }

    @Override
    public TurnoverReportVO TurnoverStatistics(LocalDate begin, LocalDate end) {

        List<Double> turnoverList = new ArrayList<>();
//        日期区间转日期集合
        List<LocalDate> localDateList = LocalDateIntervalToList(begin, end);
//        日期集合转字符串
        String dateListJoin = StringUtils.join(localDateList, ",");
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateListJoin);
        for (LocalDate localDate : localDateList) {
            Map<String, Object> hashMap = LocalDateToLocalDateTimeMap(localDate);
            hashMap.put("status", Orders.COMPLETED);
            Double turnover = ordersMapper.sumByMap(hashMap);
            turnover = turnover == null ? 0.0 :turnover;
            turnoverList.add(turnover);
        }

        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList,","));
        return turnoverReportVO;
    }

    @Override
    public UserReportVO UserStatistics(LocalDate begin, LocalDate end) {
//        日期区间转日期集合
        List<LocalDate> localDateList = LocalDateIntervalToList(begin, end);
//        日期集合转字符串
        String dateListJoin = StringUtils.join(localDateList, ",");
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(dateListJoin);
        List<Integer> countUserList = new ArrayList<>();
        List<Integer> countNewUsersList = new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            Map<String, Object> hashMap = LocalDateToLocalDateTimeMap(localDate);
            Integer countUser = userMapper.countUserByMap(hashMap);
            Integer countNewUsers = userMapper.countNewUsersByMap(hashMap);
            countUser = countUser == null ? 0 : countUser;
            countNewUsers = countNewUsers == null ? 0 : countNewUsers;
            countUserList.add(countUser);
            countNewUsersList.add(countNewUsers);
        }
        userReportVO.setTotalUserList(StringUtils.join(countUserList, ","));
        userReportVO.setNewUserList(StringUtils.join(countNewUsersList, ","));

        return userReportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = LocalDateIntervalToList(begin, end);
        String dateListJoin = StringUtils.join(localDateList, ",");
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(dateListJoin);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            Map<String, Object> map = LocalDateToLocalDateTimeMap(localDate);
            Integer orderCount = ordersMapper.getOrderCount(map);
            orderCount = orderCount == null ? 0 : orderCount;
            map.put("status",Orders.COMPLETED);
            Integer everydayValidOrderCount = ordersMapper.getOrderCount(map);
            everydayValidOrderCount = everydayValidOrderCount == null ? 0 : everydayValidOrderCount;
            orderCountList.add(orderCount);
            validOrderCountList.add(everydayValidOrderCount);
        }

        Integer totalOrderCount = 0;
        for (Integer integer : orderCountList) {
            totalOrderCount += integer;
        }
        Integer validOrderCount = 0;
        for (Integer integer : validOrderCountList) {
            validOrderCount += integer;
        }
        Double orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList,","));  //每日订单数
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));//每日有效订单数
        orderReportVO.setTotalOrderCount(totalOrderCount);//订单总数
        orderReportVO.setValidOrderCount(validOrderCount);//有效订单数
        orderReportVO.setOrderCompletionRate(orderCompletionRate);//订单完成率
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = ordersMapper.getSalesTop10(beginTime, endTime);
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        salesTop10ReportVO.setNameList(StringUtils.join(nameList,","));//商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList,","));//销量列表，以逗号分隔，例如：260,215,200
        return salesTop10ReportVO;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询近30天数据
        LocalDateTime begin = LocalDateTime.of(LocalDate.now().minusDays(30), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(begin,end);

        //2.导入Excel中

        try {
            FileInputStream fileInputStream = new FileInputStream("D:\\workspace\\sky-take-out\\运营数据报表模板.xlsx");
            //基于模板文件创建一个新的文件
            XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
            //填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin.toLocalDate()+"至"+end.toLocalDate());
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDateTime dateBegin = LocalDateTime.of(begin.plusDays(i).toLocalDate(), LocalTime.MIN);
                LocalDateTime dateEnd = LocalDateTime.of(begin.plusDays(i).toLocalDate(), LocalTime.MAX);
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(dateBegin, dateEnd);
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(dateBegin.toLocalDate().toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            }
            //3.通过输出流给客户端下载
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭流
            excel.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
